package mapper

import (
	"bytes"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"
	"gorm.io/gorm"
)

type UserMapper struct {
}

const sqlColumn = "user_id,username,password,salt,email,mobile,status,dept_id,create_time"
const defaultWhere = "1=1"

func NewUserMapper() *UserMapper {
	return &UserMapper{}
}

func (mapper *UserMapper) SelectOne(db *gorm.DB, bo bo.UserInfoBO) (entity.SysUserEntity, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	var user entity.SysUserEntity
	logx.Infof(whereSql.String())
	tx = tx.Select(sqlColumn).Where(whereSql.String()).First(&user)
	return user, tx.Error
}

func (mapper *UserMapper) getAllWhereSql(bo bo.UserInfoBO) bytes.Buffer {
	var whereSql bytes.Buffer
	whereSql.WriteString(defaultWhere)
	if bo.UserId > 0 {
		whereSql.WriteString(fmt.Sprintf(" and user_id =%d", bo.UserId))
	}
	if len(bo.Username) > 0 || bo.Username != "" {
		whereSql.WriteString(fmt.Sprintf(" and username ='%s'", bo.Username))
	}
	if len(bo.Password) > 0 || bo.Password != "" {
		whereSql.WriteString(fmt.Sprintf(" and password ='%s'", bo.Password))
	}
	if len(bo.Salt) > 0 || bo.Salt != "" {
		whereSql.WriteString(fmt.Sprintf(" and salt =%s", bo.Salt))
	}
	if len(bo.Email) > 0 || bo.Email != "" {
		whereSql.WriteString(fmt.Sprintf(" and email ='%s'", bo.Email))
	}
	if len(bo.Mobile) > 0 || bo.Mobile != "" {
		whereSql.WriteString(fmt.Sprintf(" and mobile ='%s'", bo.Mobile))
	}
	if bo.Status > 0 {
		whereSql.WriteString(fmt.Sprintf(" and status =%d", bo.Status))
	}
	if bo.DeptId > 0 {
		whereSql.WriteString(fmt.Sprintf(" and dept_id =%d", bo.DeptId))
	}
	if bo.StartTime != nil {
		whereSql.WriteString(fmt.Sprintf(" and create_time >='%s'", bo.StartTime))
	}
	if bo.EndTime != nil {
		whereSql.WriteString(fmt.Sprintf(" and update_tim <'%s'", bo.EndTime))
	}
	return whereSql
}

func (mapper *UserMapper) SelectCount(db *gorm.DB, bo bo.UserInfoBO) (int64, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	var total int64
	userEntity := entity.SysUserEntity{}
	tx = tx.Select(sqlColumn).Table(userEntity.TableName()).Where(whereSql.String()).Count(&total)
	return total, tx.Error
}

func (mapper *UserMapper) SelectList(db *gorm.DB, bo bo.UserInfoBO) ([]entity.SysUserEntity, error) {
	tx := db.Session(&gorm.Session{SkipDefaultTransaction: true})
	whereSql := mapper.getAllWhereSql(bo)
	whereSql.WriteString(" order by create_time desc")
	var retList []entity.SysUserEntity
	if bo.PageSize > 0 {
		// 查询语句
		tx = tx.Select(sqlColumn).Where(whereSql.String()).Offset(bo.StartIndex).Limit(bo.PageSize).Find(&retList)
	} else {
		// 查询语句
		tx = tx.Select(sqlColumn).Where(whereSql.String()).Find(&retList)
	}
	return retList, tx.Error
}
